package com.zoro.dyformservice.support.web.converter;

import com.zoro.dyformservice.interfaces.CodeData;
import com.zoro.dyformservice.utils.StringUtils;
import jakarta.annotation.Nonnull;
import org.springframework.format.Formatter;

import java.text.ParseException;
import java.util.Locale;

public class CodeDataFormatter<T extends CodeData> implements Formatter<T> {

    private final Class<T> tClass;

    public CodeDataFormatter(Class<T> tClass) {
        if (tClass == null) {
            throw new IllegalArgumentException("class can not be null.");
        }
        if (!tClass.isEnum()) {
            throw new IllegalArgumentException("class can not be null and must be a enum :" + tClass.getName());
        }
        this.tClass = tClass;
    }

    @Override
    public T parse(@Nonnull String text, @Nonnull Locale locale) throws ParseException {
        if (StringUtils.isBlank(text)) {
            return null;
        }
        T[] values = tClass.getEnumConstants();
        for (T t : values) {
            if (StringUtils.equal(t.getCode(), text)) {
                return t;
            }
        }
        return null;
    }

    @Override
    public String print(T object, Locale locale) {
        if (object == null) {
            return null;
        }
        return object.getCode();
    }
}
